package com.slashvision.im.tool

import android.annotation.SuppressLint
import android.content.Context
import android.database.Cursor
import android.graphics.Bitmap
import android.media.MediaMetadataRetriever
import android.net.Uri
import android.provider.MediaStore
import com.slashvision.im.ContextUtil
import com.slashvision.im.SLog
import com.slashvision.im.TAG
import com.slashvision.im.bean.VideoInfo
import com.slashvision.im.chat.TAG_IM
import com.slashvision.im.toastShort
import java.io.File
import java.io.FileOutputStream


/**
 * author : lizhenxin
 *  date  : 2021/10/18
 *  desc  :
 */
/**
 * @desc:
 * @author: LiZhenxin
 * @create:
 * update
 **/
object FileUtil {
    fun getVideoInfo(path:String): VideoInfo? {
        val mmr = MediaMetadataRetriever()
        try {
            var headers = mutableMapOf<String, String>()
            headers["User-Agent"] =
                "Mozilla/5.0 (Linux; U; Android 4.4.2; zh-CN; MW-KW-001 Build/JRO03C) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 UCBrowser/1.0.0.001 U4/0.8.0 Mobile Safari/533.1"
            SLog.d(TAG_IM, "视频地址： ${path}")
            mmr.setDataSource(path)
            val duration =
                mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLong() //时长(毫秒)
            val mimetype = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE)
//            val videoPath = StorgeUtil.getPathFromUri(ContextUtil.getContext(), uri)
            val thumbnailPath = getThumbnailPath(mmr, path)
            SLog.d(TAG_IM, "缩略图路径：${thumbnailPath}")
            return VideoInfo(path, mimetype ?: "", duration ?: 0L, thumbnailPath)
        } catch (ex: Exception) {
            SLog.e(this.TAG(), "获取视频信息错误: ${ex.cause},  ${ex.message}")
            ContextUtil.getContext().toastShort("获取视频信息错误")
        } finally {
            mmr.release()
        }

        return null
    }


    private fun getThumbnailPath(mmr: MediaMetadataRetriever, path:String): String {
        val name = getVideoNameFromUri(path)
        val f = File(StorgeUtil.pictureCacheDir, "${name}.jpg")
        try {
            mmr.frameAtTime?.let { bitmap ->
                FileOutputStream(f).use {
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, it)
                    it.flush()
                }
            }
        } catch (e: Exception) {
            SLog.e(TAG_IM, "getThumbnailPath error: ${e}")
        }
        return f.absolutePath
    }

    private fun getVideoNameFromUri(path:String): String {
        return path.substring(
            path.lastIndexOf("/"),
            path.lastIndexOf(".")
        )
    }

    /*
    var thumbColumns = arrayOf(MediaStore.Video.Thumbnails.DATA)
    var mediaColumns = arrayOf(MediaStore.Video.Media._ID)

    @SuppressLint("Range")
    fun getThumbnailPathForLocalFile(
        fileUri: Uri
    ): String {
        val fileId = getFileId(fileUri)
        MediaStore.Video.Thumbnails.getThumbnail(
            ContextUtil.getContext().getContentResolver(),
            fileId, MediaStore.Video.Thumbnails.MICRO_KIND, null
        )
        ContextUtil.getContext().contentResolver.query(
            MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,
            thumbColumns, MediaStore.Video.Thumbnails.VIDEO_ID + " = "
                    + fileId, null, null
        )?.use {
            if (it.moveToFirst()) {
                return it.getString(it.getColumnIndex(MediaStore.Video.Thumbnails.DATA))
            }

        }
        return ""
    }

    fun getFileId(fileUri: Uri): Long {
        ContextUtil.getContext().contentResolver.query(
            fileUri, mediaColumns, null, null,
            null
        )?.use {
            if (it.moveToFirst()) {
                val columnIndex = it
                    .getColumnIndexOrThrow(MediaStore.Video.Media._ID)
                val id = it.getInt(columnIndex)
                return id.toLong()
            }
        }

        return 0
    }*/
}